package demo4.controller;

import demo4.mapper.IUserMapper;
import demo4.mapper.UserMapper;
import demo4.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Scanner;

/**
 * Controller 控制器，后面学习SpringMVC时会介绍到
 * 这里简单理解
 * 它负责和客户端(用户打交道)
 */
@Component
public class UserController {
    @Autowired
    private IUserMapper userMapper;

    public void start(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入序号:");
        System.out.println("1:用户注册");
        System.out.println("2:用户登录");
        System.out.println("3:修改密码");
        System.out.println("4:用户列表");
//        System.out.println("5:....");
        int num = scanner.nextInt();
        switch (num){
            case 1:
                regUser();
                break;
            case 2:
                loginUser();
                break;
            case 3:
                System.out.println("修改密码");
                break;
            case 4:
                showUserList();
                break;
        }
    }
    private void showUserList(){
        System.out.println("用户列表");
        for(UserInfo userInfo : userMapper.selectAll()){
            System.out.println(userInfo);
        }
    }

    private void loginUser(){
        System.out.println("欢迎登录");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        //根据用户名查询该用户
        UserInfo userInfo = userMapper.selectByUsername(username);
        if(userInfo!=null){
            if(userInfo.getPassword().equals(password)){//密码正确
                System.out.println("登录成功,欢迎["+userInfo.getNickname()+"]回来");
            }else{
                System.out.println("密码错误");
            }
        }else{
            System.out.println("该用户不存在");
        }

    }

    private void regUser(){
        /*
            注册流程
            1:获取用户输入的注册信息
            2:后期可以做相应的正确性，完整性验证
            3:插入数据库
            4:返回结果给用户
         */
        UserInfo userInfo = new UserInfo();
        System.out.println("欢迎注册");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        userInfo.setUsername(scanner.nextLine());
        System.out.println("请输入密码:");
        userInfo.setPassword(scanner.nextLine());
        System.out.println("请输入昵称:");
        userInfo.setNickname(scanner.nextLine());
        System.out.println("请输入年龄:");
        userInfo.setAge(scanner.nextInt());
        //2:后期可以补充验证操作

        //3:插入数据库
        int num = userMapper.insert(userInfo);
        if(num > 0){
            System.out.println("注册成功");
        }else{
            System.out.println("注册失败");
        }
    }
}
